<?php
/**
 * Sites handler
 * 
 * Actions
 *		Edit: displays form to edit the specified site
 *		Add: displays form to add the specified site
 *		Save: saves the changes
 *		Delete: removes the specified site
 *		Code: displays help on how to add tracking code in the specified website
 *		
 */
require_once dirname(dirname(__FILE__)) .'/cse-init.php';

// authentication is required!
Cinnamon::registry('session')->applyAuthenticationPolicy(true);

// fetch required objects from Cinnamon registry
$params = Cinnamon::registry('params');
$view = Cinnamon::registry('view');
$db = Cinnamon::registry('db');
$config = Cinnamon::registry('config');

// handle the requested action
switch ( $params->action ) {
	case 'edit':		// display form to edit a site
		$sql = "SELECT * FROM $db->sites WHERE site_id=". $db->escape($params->site_id);
		$view->setVariable('site', $db->getRecord($sql));
		
		// Itterator could be used here for queries like "%track.downloads%"
		$sql = "SELECT * FROM $db->options WHERE option_name = 'track.downloads.site.".$params->site_id."'";
		$view->setVariable('track_site', $db->getRecord($sql));
		
		$sql = "SELECT * FROM $db->options WHERE option_name = 'track.downloads.extensions.site.".$params->site_id."'";
		$view->setVariable('track_site_extensions', $db->getRecord($sql));
		
	case 'add':			// display form to add a site
		$view->renderHeader();
		$view->render('sites-edit.php');
		$view->renderFooter();		
		break;
	case 'save':		// save the site (perfoms an insert or update)
		// Fix URLs by adding http://
		if ( !preg_match('!^https?://!i', $params->site_url) ) {
			$params->site_url = 'http://'. $params->site_url;
		}
		$params->ignore_www = ( empty($params->ignore_www) ) ? 'n' : 'y';
		$params->match_subdomains = ( empty($params->match_subdomains) ) ? 'n' : 'y';
		
		$params->track_downloads = ( empty($params->track_downloads) ) ? 'n' : 'y';
	
		$params->tracked_extensions = ($params->track_downloads=='n') ? '' : $params->tracked_extensions ;
		
		if ($params->tracked_extensions!='')
			$extensionsArray = explode(",",$params->tracked_extensions);
		
		if ($params->track_downloads=='y'){	//if user wants to track downloads check if options exists and then update
			if ( !$config->exists('track.downloads.site.'.$params->site_id) ) {
				$config->add('track.downloads.site.'.$params->site_id, 'y', 'y');
				$config->add('track.downloads.extensions.site.'.$params->site_id, $extensionsArray, 'y');
			} else {
				$config->set('track.downloads.site.'.$params->site_id, 'y', 'y');
				$config->set('track.downloads.extensions.site.'.$params->site_id, $extensionsArray, 'y');
			}
		} else { //if user does not want to track downloads check if options exists and then update
			if ( !$config->exists('track.downloads.site.'.$params->site_id) ) {
				$config->add('track.downloads.site.'.$params->site_id, 'n', 'y');
				$config->add('track.downloads.extensions.site.'.$params->site_id, '', 'y');
			} else {
				$config->set('track.downloads.site.'.$params->site_id, 'n', 'y');
				$config->set('track.downloads.extensions.site.'.$params->site_id, $extensionsArray, 'y');
			}	
		}
		

		if ( isset($params->site_id) && is_numeric($params->site_id) ) {
			$sql = "UPDATE $db->sites "
				  ."SET site_url='". $db->escape($params->site_url) ."', "
				  ."site_name='". $db->escape($params->site_name) ."', "
				  ."ignore_www='". $db->escape($params->ignore_www) ."', "
				  ."match_subdomains='". $db->escape($params->match_subdomains) ."', "				  
				  ."utc_offset='". $db->escape($params->utc_offset) ."' "
				  ."WHERE site_id=". intval($params->site_id);
			$db->query($sql);
			header("Location: sites.php?updated=true");
		} else {
			$sql = "INSERT INTO $db->sites "
				  ."(site_url, site_name, ignore_www, match_subdomains, utc_offset) "
				  ."VALUES('". $db->escape($params->site_url) ."', '". $db->escape($params->site_name) ."', '". $db->escape($params->ignore_www) ."', '". $db->escape($params->match_subdomains) ."', '". $db->escape($params->utc_offset) ."')";
			$db->query($sql);
			header("Location: sites.php?action=code&updated=true&site_id=". $db->insertId());	
		}	
		break;
	case 'delete':		// removes a site
		// delete site from sites table
		$sql = "DELETE FROM $db->sites "
			  ."WHERE site_id=". intval($params->site_id);
		$db->query($sql);
		// delete tracked requests
		$sql = "DELETE FROM $db->requests "
			  ."WHERE site_id=". intval($params->site_id);
		$db->query($sql);
		// optimize tables
		$db->query("OPTIMIZE TABLE ". $db->requests);
		header("Location: sites.php?deleted=true");	
		break;
	case 'help':		// display help after adding a site
		$view->clearMessages();
		
		$view->setVariable('updated', $params->updated);

		$sql = "SELECT * FROM $db->sites WHERE site_id=". $db->escape($params->site_id);
		$view->setVariable('site', $db->getRecord($sql));

		$view->renderHeader();
		$view->render('sites-help.php');
		$view->renderFooter();		
		break;
	case 'status':
		break;	
	default:
		$view->clearMessages();
		if ( $params->updated == 'true' ) {
			$view->addMessage(View::NOTICE, 'Site has been updated successfully.');
		} else if ( $params->deleted == 'true' ) {
			$view->addMessage(View::NOTICE, 'Site has been removed successfully.');		
		}
		
		// fetch sites
		$sql = "SELECT * FROM $db->sites ORDER BY site_id ";
		$sites = $db->getIterator($sql);
		$view->setVariable('sites', $sites);
		
		// check their status
		$hasCode = array();
		$lastSite = null;
		foreach ( $sites as $site ) {
			if ( strcmp($site->has_code, 'n') == 0 ) {
				// check status via http request
				Cinnamon::loadClass('URLConnection');
				Cinnamon::loadClass('URLReader');
				$r = new URLReader($site->site_url);
				$hasCode[$site->site_id] = ( $r->hasCinnamonCode($site->site_id) ) ? 'y' : 'n';	
				unset($r);
				
				// updates its status if necessary
				if ( strcmp($hasCode[$site->site_id], 'y') == 0 ) {
					$sql = "UPDATE ". $db->sites ." SET has_code='y' WHERE site_id=". $site->site_id;
					$db->query($sql);
				} else {
					$lastSite = $site;
				}
			} else {
				$hasCode[$site->site_id] = 'y';
			}
		}
		$view->setVariable('hasCode', $hasCode);
		
		
		$values = array_count_values($hasCode);
		if ( $values['n'] == 1 ) {
			$view->addMessage(View::WARNING, 'One of the websites, &ldquo;'. $lastSite->site_name .'&rdquo;, does not contain Cinnamon Statistics Engine tracking code, which is essential for gathering statistics. <a href="sites.php?action=help&amp;site_id='. $lastSite->site_id .'">Learn how you can add the tracking code in that website &raquo;</a>.');		
		} else if ( $values['n'] > 1 ) {
			$view->addMessage(View::WARNING, 'Some of the websites do not contain Cinnamon Statistics Engine tracking code, which is essential for gathering statistics. Those websites have been marked for your convenience. Use the &rdquo;More link&rdquo; under each website, for assistance on how to add the tracking code.');		
		}
		
		// render output
		$view->renderHeader();
		$view->render('sites-list.php');
		$view->render('sites-edit.php');
		$view->renderFooter();
		break;
}
